const express = require('express');
const router = express.Router();
const path = require('path')
const mongoose = require("mongoose");
const moment = require('moment');

// 导入lowdb
const low = require('lowdb')
const FileSync = require('lowdb/adapters/FileSync')
const adapter = new FileSync(path.resolve(__dirname, '../data/db.json'))
// 获取db对象
const db = low(adapter)
const shortid = require('shortid');
const {accountSchema, accountModel} = require("../data/modules/accounts");


/* GET home page. */
router.get('/', function (req, res, next) {
    res.redirect('/account')
});

router.get('/account', function (req, res, next) {
    // let accounts = db.get('accounts').value();
    let accounts;
    accountModel.find().sort({time:-1}).exec().then(resolve => {
        res.render('index', {accounts: resolve});
    })

});

router.get('/account/create', function (req, res, next) {
    res.render('create');
});


router.post('/account/create',   function (req, res, next) {

    accountModel.create({
        ...req.body,
        // time:moment(req.body.time).toDate() //修改time的属性值
    }).then(resolve => {
        console.log(resolve)
        res.render('success', {message: '添加成功~~~', url: '/account'});
    }).catch((error) => {
        console.log('错误啦！！！:', error);
        res.status(500)
        res.render('fail', {message: '添加失败~~~', url: '/account/create'});
        return;
    })


})


router.get('/account/create/:id', function (req, res, next) {
    let id = req.params.id;
    accountModel.deleteOne({_id:id}).then(resolve => {
        res.render('success', {message: '删除成功~~~', url: '/account'});
    })
});


module.exports = router;
